package com.javalsj.common.web.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.javalsj.common.base.exception.BusinessRuntimeException;
import com.javalsj.common.base.http.BusinessResponseEntity;

/**
 * @description 全局异常处理
 * @author WANGJIHONG
 * @date 2018年7月30日 下午12:20:01 
 * @Copyright 版权所有 (c) www.javalsj.com
 * @memo 无备注说明
 */
@RestControllerAdvice
public class BusinessExceptionHandler {

	public static final Logger LOGGER = LoggerFactory.getLogger(BusinessExceptionHandler.class);

	@ExceptionHandler(MethodArgumentNotValidException.class)
	public <T> BusinessResponseEntity<T> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
		String msg = "未知的参数异常";
		BindingResult bindingResult = e.getBindingResult();
		if (bindingResult.hasErrors()) {
			msg = bindingResult.getAllErrors().stream().map(error -> error.getDefaultMessage()).reduce("", (s1, s2) -> s1 + "\n" + s2);
		}
		return BusinessResponseEntity.error(msg);
	}
	
	@ExceptionHandler(BusinessRuntimeException.class) 
	public <T> BusinessResponseEntity<T> handleGCRuntimeException(BusinessRuntimeException e) {
		LOGGER.error(e.getMessage(), e);
		return BusinessResponseEntity.error(e);
	}

	@ExceptionHandler(Exception.class)
	public <T> BusinessResponseEntity<T> handleException(Exception e) {
		LOGGER.error(e.getMessage(), e);
		return BusinessResponseEntity.error(e);
	}
	
}
